// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#include <cantor/parser/parser.h>
#include <cantor/transform/ddls/table_partition_option.h>
#include <cantor/transform/ddls/table_option.h>
#include <cantor/transform/exprs/constant_expr.h>

namespace cantor::transform {

    void TransTableOption::resolve_ast(const cantor::parser::TableOption*node) {
        if (!node) {
            status = turbo::data_loss_error("no expr");
            return;
        }

        table_option.set_type(node->type);
        table_option.set_str_value(node->str_value.to_string());
        table_option.set_int_value(node->uint_value);
        if (node->partition) {
            TransTablePartitionOption ops;
            ops.resolve_ast(node->partition);
            status = ops.check();
            if (!status.ok()) {
                return;
            }
            *table_option.mutable_partition() =  std::move(ops.table_partition_option);
        }
        set_proto_location(node, table_option.mutable_location());
        set_proto_status(table_option.mutable_status());
    }

    const turbo::Status &TransTableOption::check() {
        if (!status.ok()) {
            return status;
        }
        if (!table_option.has_location()) {
            make_missing_required_field("location");
            return status;
        }
        return status;
    }

    turbo::Status TransTableOption::resolve_to(turbo::Nonnull<const cantor::parser::TableOption*> arg, turbo::Nonnull<pb::ast::TableOption *>out) {
        TransTableOption trans;
        trans.resolve_ast(arg);
        auto status = trans.check();
        if (!status.ok()) {
            return status;
        }
        *out = std::move(trans.table_option);
        return status;
    }
}  // namespace cantor::transform
